package com.smm.web.vmc.util;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

/**
 * <p>
 * 	协议解码器
 * </p>
 * @author 曾世华
 * @date 2016年1月21日
 * @version 1.0
 *
 */
public class ByteArrayDecoder extends CumulativeProtocolDecoder {
	
	
	@Override
	public boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {
		//in.prefixedDataAvailable(1, 19)
		int i=1;
		String frist="";
		String result ="";
		
		while (in.hasRemaining()) {
			
			byte data =in.get();
			
			if(frist.equals("")){
				frist= Integer.toHexString(data & 0xff);
			}
			//以13开头，连续读取20字节
			if(frist.equals("13")){
				
				if(i<=20){
					result+=Integer.toHexString(data & 0xff).length()==1?"0"+Integer.toHexString(data & 0xff): Integer.toHexString(data & 0xff);
					if(i==20){
						out.write(result);
					}
					i++;
				}else{
					//重置。读取下一条消息
					i=1;
					frist="";
					result="";
				}
			}
//			System.out.println("i==="+i);
		}
		/**
		 * 当这次读完毕
		 */
        return i >= 20;
	}

}
